﻿using Markdig;
using Microsoft.Web.WebView2.Core;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace LPBToolsNF
{
    public partial class WMarkDownBox : UserControl
    {
        /// <summary>
        /// 本地文件地址头，在此头后面加上文件名，即可访问本地文件
        /// </summary>
        public const string uriLocalFileHeader = "https://file.lpbstudio.com/";
        public WMarkDownBox()
        {
            InitializeComponent();
            // 在设计时禁用 WebView2 初始化
            if (LicenseManager.UsageMode == LicenseUsageMode.Designtime)
            {
                webView2MDInfo.Visible = false;
                return;
            }
            InitializeWebView2Async();
        }

        private async void InitializeWebView2Async()
        {
            try
            {
                // 确保WebView2已初始化
                if (webView2MDInfo.CoreWebView2 == null)
                {
                    // 确保环境已初始化
                    if (!WebView2EnvironmentManager.Instance.IsInitialized)
                        await WebView2EnvironmentManager.Instance.InitializeAsync();
                    await webView2MDInfo.EnsureCoreWebView2Async(WebView2EnvironmentManager.Instance.Environment);
                }
                // 初始化WebView2消息处理
                webView2MDInfo.CoreWebView2.NavigationStarting += CoreWebView2_NavigationStarting;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"初始化WebView2时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        // 处理导航事件，拦截本地文件链接
        private void CoreWebView2_NavigationStarting(object sender, Microsoft.Web.WebView2.Core.CoreWebView2NavigationStartingEventArgs e)
        {
            string uri = e.Uri.ToLower();

            // 检查是否是本地文件链接
            if (uri.StartsWith(uriLocalFileHeader))
            {
                // 取消默认导航
                e.Cancel = true;
                try
                {
                    // 转换为本地文件路径
                    string localPath = uri.Replace(uriLocalFileHeader, "");

                    // 处理空格和特殊字符
                    localPath = System.Web.HttpUtility.UrlDecode(localPath);

                    // 使用系统默认程序打开文件
                    System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
                    {
                        FileName = localPath,
                        UseShellExecute = true
                    });
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"无法打开文件: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            if (uri.StartsWith("http"))
            {
                // 取消默认导航
                e.Cancel = true;
            }
        }

        /// <summary>
        /// MarkDown 换行间隔，默认为1.5
        /// </summary>
        public decimal LineSpacing
        {
            get { return _lineSpacing; }
            set
            {
                if (value > 0.2m)
                    UpdateLineSpacing(value);
            }
        }

        decimal _lineSpacing = 1.5m;

        private void UpdateLineSpacing(decimal spacing)
        {
            _lineSpacing = spacing;
            if (webView2MDInfo.CoreWebView2 != null)
            {
                string script = $"document.documentElement.style.setProperty('--line-spacing', '{_lineSpacing}');";
                webView2MDInfo.CoreWebView2.ExecuteScriptAsync(script);
            }
        }

        /// <summary>
        /// 获取或设置MarkdownBox的背景颜色
        /// </summary>
        public Color BackColor_MDBox
        {
            get { return this.BackColor; }
            set
            {
                if (this.BackColor != value)
                {
                    this.BackColor = value;
                    showMarkDownInfo(sMDText);
                }
            }
        }

        /// <summary>
        /// 获取或设置MarkdownBox的当前文本
        /// </summary>
        public string MarkDownText { get { return sMDText; } set { showMarkDownInfo(value); } }

        protected string sMDText = "";

        /// <summary>
        /// 将字符串绘制到MarkdownBox
        /// </summary>
        /// <param name="sMarkDownText"></param>
        public async void showMarkDownInfo(string sMarkDownText)
        {
            sMDText = sMarkDownText;
            // 转换 Markdown 并保存为 HTML
            var pipeline = new MarkdownPipelineBuilder().UseAdvancedExtensions()
                .UseSyntaxHighlighting()  // 启用语法高亮
                .Build();
            string html = Markdown.ToHtml(sMarkDownText, pipeline);

            // 包装HTML并设置背景色（与WinForms窗体背景色一致）
            string styledHtml = $@"
<!DOCTYPE html>
<html lang='zh-CN'>
<head>
<meta charset='UTF-8'>
    <style>
        :root {{
            --line-spacing: {_lineSpacing}; /* 行间距变量 */
        }}
        body {{ 
            background-color: {ColorTranslator.ToHtml(this.BackColor)};
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            margin: 0;
            line-height: var(--line-spacing)!important; /* 应用行高变量 */
        }}
        
        /* 所有代码块统一黑色背景白色文字 */
        pre {{
            background-color: #111;
            color: #EEE;
            padding: 10px;
            border-radius: 4px;
            overflow-x: auto;
            font-family: Consolas, monospace;
        }}       
    </style>
</head>
<body>
    {html}
</body>
</html>";
            // 确保WebView2已初始化
            if (webView2MDInfo.CoreWebView2 == null)
            {
                // 确保环境已初始化
                if (!WebView2EnvironmentManager.Instance.IsInitialized)
                    await WebView2EnvironmentManager.Instance.InitializeAsync();
                await webView2MDInfo.EnsureCoreWebView2Async(WebView2EnvironmentManager.Instance.Environment);
            }
            webView2MDInfo.CoreWebView2.NavigateToString(styledHtml);
        }

        public static string[] DemoTexts = new string[]
        {
            "# Markdown实时渲染演示",
                "",
                "这个演示展示了如何在Windows Forms应用中逐行显示Markdown内容。",
                "",
                "## 主要特性",
                "- 使用MarkDig进行Markdown到HTML的转换",
                "- 使用WebView2渲染HTML内容",
                "- 逐条显示Markdown内容，带有平滑动画效果",
                "- 完全离线运行，无需联网",
                "- 自动同步主窗体背景色",
                "",
                "## 支持的Markdown语法",
                "MarkDig支持广泛的Markdown语法，包括：",
                "",
                "### 标题",
                "# 一级标题",
                "## 二级标题",
                "### 三级标题",
                "",
                "### 文本格式",
                "**加粗文本**",
                "*斜体文本*",
                "***加粗斜体***",
                "~~删除线~~",
                "",
                "### 列表",
                "1. 有序列表项1",
                "2. 有序列表项2",
                "   - 无序列表子项1",
                "   - 无序列表子项2",
                "",
                "# 标题\n**加粗文本** *斜体文本* [链接](https://example.com)",
                "",
                "<span style=\"color:red\">这是红色文本</span>。",
                "",
                "<span style=\"color:blue\">这是蓝色文本</span>。",
                "",
                "这是一个 SVG 图标：<svg width=\"16\" height=\"16\" viewBox=\"0 0 24 24\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\r\n  <path d=\"M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg>",
                "",
                "这是一个 SVG 图标：<svg width=\"16\" height=\"16\" viewBox=\"0 0 24 24\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\r\n  <path d=\"M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5\" stroke=\"red\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg>",
                "",
                "这是一个 SVG 图标：<svg width=\"16\" height=\"16\" viewBox=\"0 0 24 24\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\r\n  <path d=\"M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5\" stroke=\"blue\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg>",
                "",
                "[打开本地 PDF 文件]("+uriLocalFileHeader+"E:/demo.pdf)",
                "",
                "### 代码块",
                "```csharp\r\npublic class Program {\r\n    public static void Main() {\r\n        Console.WriteLine(\"Hello, Markdown!\");\r\n    }\r\n}\r\n```",
                "",
                "```python\r\ndef hello_world():\r\n    print(\"Hello, Markdown!\")\r\n\r\nif __name__ == \"__main__\":\r\n    hello_world()\r\n```",
                "",
                "```javascript\r\nfunction sayHello() {\r\n    console.log(\"Hello, Markdown!\");\r\n}\r\n```",
                "",
                "### 引用",
                "> 这是一个引用块\r\n> 可以包含多行文本",
                "",
                "### 表格",
                "| 列1 | 列2 | 列3 |\r\n|-----|-----|-----|\r\n| 值1 | 值2 | 值3 |\r\n| 值4 | 值5 | 值6 |",
                "",
                "## 实时渲染效果",
                "您现在看到的内容就是逐条添加并渲染的。每一行Markdown都在收到后立即转换为HTML并显示，同时保持良好的格式和动画效果。",
                "",
                "试试看切换主题，看看背景色是如何自动同步的！"
        };
    }
}
